﻿using System;
using System.Collections.Generic;
using System.Text;
using Dora.Tools.Utility.Const;
using Surging.Core.CPlatform.Ioc;
using Dora.Services.AdminUser.Application.Base;
using Dora.Services.AdminUser.Entities;
using Dora.Services.AdminUser.IApplication;
using Dora.Orm.SqlSugarCore.UnitOfWork;
using Dora.Services.AdminUser.Repository.Repositorys;
using System.Threading.Tasks;
using Surging.Core.Common;

namespace Dora.Services.AdminUser.Application
{
    /// <summary>
    /// 参数映射表服务
    /// </summary>
    [ModuleName(DoraModuleName.AdminUser)]
    public class ParamsMapService : DoraServiceBase, IParamsMapService
    {

        private ISugarUnitOfWork _unitOfWork;
        private readonly ParamsMapRepository _repository;
        public ParamsMapService(ISugarUnitOfWork unitOfWork)
        {
            _unitOfWork = unitOfWork;
            _repository = new ParamsMapRepository(unitOfWork);
        }
        /// <summary>
        /// 根据参数以及参数类型获取表信息
        /// </summary>
        /// <param name="Params"></param>
        /// <param name="Type"></param>
        public async Task<ParamsMapEntity> GetInfoByParams(ParamsMapEntity entity)
        {
            var result = await _repository.GetInfoByParams(entity);
            //如果参数映射已经存在
            if (result != null)
            {
                //更新    更新时间  更新人  更新人ID
                _ = await _repository.UpdateInfo(result);
            }
            //如果参数映射不存在则新增
            else
            {
                if (!string.IsNullOrWhiteSpace(entity.ParamsValue) && entity.ParamsType > 0)
                {
                    entity.CreatedUserId = entity.UpdatedUserId;
                    entity.CreatedUserName = entity.UpdatedUserName;
                    entity.CreatedTime = entity.UpdatedTime;
                    result = await _repository.InsertAsync(entity);
                }
            }
            return result;
        }

        /// <summary>
        /// 创建
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<ResultDto<int>> Create(ParamsMapEntity entity)
        {
            var result = await _repository.InsertAsync(entity);
            return ResultDto<int>.Success(result.Id);
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<bool> Update(ParamsMapEntity entity)
        {
            var result = await _repository.UpdateInfo(entity);
            return result;
        }

        /// <summary>
        /// 根据Id获取一个实体对象
        /// </summary>
        /// <param name="id"></param>
        public async Task<ParamsMapEntity> GetById(int id)
        {
            return await _repository.FirstOrDefaultAsync(id);
        }

    }
}
